/**
 * This file is part of RailEGo
 * Copyright (c) 2023 Guo Tingjin <dev@peercat.cn>
 * RailEGo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * RailEGo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

export function base64FromByteArray(r) {
  var u = [];
  var v = [];
  var tKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var oo = 0, a = tKey.length; oo < a; ++oo) {
    u[oo] = tKey[oo];
    v[tKey.charCodeAt(oo)] = oo;
  }
  const s = (r) => {
    return u[r >> 18 & 63] + u[r >> 12 & 63] + u[r >> 6 & 63] + u[r & 63];
  }
  const l = (r, e, n) => {
    var t;
    var o = [];
    for (var a = e; a < n; a += 3) {
      t = (r[a] << 16 & 16711680) + (r[a + 1] << 8 & 65280) + (r[a + 2] & 255);
      o.push(s(t))
    }
    return o.join("")
  }
  var e;
  var n = r.length;
  var t = n % 3;
  var o = [];
  var a = 16383;
  for (var f = 0, i = n - t; f < i; f += a) {
    o.push(l(r, f, f + a > i ? i : f + a))
  }
  if (t === 1) {
    e = r[n - 1];
    o.push(u[e >> 2] + u[e << 4 & 63] + "==")
  } else if (t === 2) {
    e = (r[n - 2] << 8) + r[n - 1];
    o.push(u[e >> 10] + u[e >> 4 & 63] + u[e << 2 & 63] + "=")
  }
  return o.join("")
}